package com.example.myapplication.ui.account

import android.content.Intent
import android.view.View
import com.example.myapplication.FileActivity
import com.example.myapplication.R
import com.example.myapplication.net.bean.request.BaseRequest
import com.example.myapplication.net.bean.request.LoginParams
import com.example.myapplication.net.bean.response.BaseResponse
import com.example.myapplication.net.bean.response.LoginBean
import com.example.myapplication.common.AbstractFragment
import com.example.myapplication.extensions.PERMISSION_READ_STORAGE
import com.example.myapplication.extensions.PERMISSION_WRITE_STORAGE
import com.example.myapplication.extensions.appConfig
import com.example.myapplication.net.AbstractCallback
import com.example.myapplication.net.ApiNetwork
import com.example.myapplication.net.ServiceApi
import com.example.myapplication.permission.Permission
import com.example.myapplication.utils.RsaUtils
/**
 * 登录Fragment
 */
class LoginFragment : AbstractFragment() {

    private val remote = ApiNetwork()
    private val permission = Permission()

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_login
    }


    override fun initView(contentView: View) {
        super.initView(contentView)
        contentView.findViewById<View>(R.id.tv_login).also {
            it.post {
                permission.handlePermission(requireActivity(), PERMISSION_WRITE_STORAGE) { write ->
                    if (write) {
                        permission.handlePermission(requireActivity(), PERMISSION_READ_STORAGE) { read ->
                            if (read) {
                                getRSAKey()
                            }
                        }
                    }
                }
            }
        }.setOnClickListener {
            getRSAKey()
        }
    }
    /**
     * 获取key并进行登录
     */
    fun getRSAKey() {
        val remote1 = remote.remote(ServiceApi::class.java, false)
        remote1.postGetRSAKey().enqueue(object : AbstractCallback<BaseResponse<String>>("") {
            override fun onSuccess(t: BaseResponse<String>) {
                val newPassword = RsaUtils.encryptDataByPublicKey(
                    "a123456",
                    RsaUtils.keyStrToPublicKey(t.data)
                )
                remote1.postLoginData(BaseRequest<LoginParams>().apply {
                    this.data = LoginParams().apply {
                        this.password = newPassword
                        this.publicKey = t.data!!
                        this.username = "wyz"
                    }
                }).enqueue(object : AbstractCallback<BaseResponse<LoginBean>>("app/sys/login") {
                    override fun onSuccess(t: BaseResponse<LoginBean>) {
                        requireActivity().appConfig.token = t.data?.token
                        requireActivity().appConfig.userId = t.data?.userInfo?.id ?: -1
                        checkNullOrEmpty({
                            val activity = requireActivity()
                            if (activity is FileActivity) {
                                activity.loadFragment( FileFragment(), true)
                            }
                        }, requireActivity().appConfig.token, requireActivity().appConfig.userId)
                    }
                })
            }
        })
    }

    fun checkNullOrEmpty(block: () -> Unit, vararg value: Any?) {
        value.forEach {
            it ?: return
            when (it) {
                is Number -> if (it == -1) return
                is String -> if (it.isEmpty()) return
            }
        }
        block.invoke()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        permission.onRequestPermissionsResult(requestCode, permissions, grantResults)
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }
}